
const { ccclass, property } = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property(cc.Node)
    target: cc.Node = null;
    @property(cc.Node)
    offset: cc.Vec2 = cc.v2()

    _tracking: boolean;
    _prevPos: cc.Vec2;
    // use this for initialization
    onLoad() {
        this._tracking = false;
        let targetTrans = this.target.getNodeToWorldTransform();
        this._prevPos = cc.v2(0, 0);

        //this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
    }

    onTouchMove(event: cc.Event.EventTouch) {
        let dx = event.getDeltaX();
        let dy = event.getDeltaY();

        this.target.x += dx;
        this.target.y += dy;
        this.cameraMove(this.target.position);
    }

    cameraMove(pos:cc.Vec3) {
        let camera = cc.Camera.cameras[0];
        let pre = camera.node.position;
        camera.node.y = pos.y;
        if (this.containsRect() == false) {
            camera.node.y = pre.y;
        }
        camera.node.x = pos.x;
        if (this.containsRect() == false) {
            camera.node.x = pre.x;
        }
    }

    isCanMove: boolean = false;
    containsRect() {
        let camera = cc.Camera.cameras[0];
        let cameraBox = camera.node.getBoundingBoxToWorld();
        let mapBox = this.node.getBoundingBoxToWorld();
        if (mapBox.containsRect(cameraBox)) {
            return true;
        }
        else {
            return false;
        }
    }

    update(dt) {

    }

    // called every frame, uncomment this function to activate update callback
    lateUpdate1(dt) {

        if (!this.target) {
            return;
        }

        let targetX = this.target.x,
            targetY = this.target.y,
            winW = cc.winSize.width,
            winH = cc.winSize.height,
            mapW = this.node.width,
            mapH = this.node.height;

        if (this._prevPos.x !== targetX || this._prevPos.y !== targetY) {
            let appx = this.node.anchorX * mapW;
            let appy = this.node.anchorY * mapH;

            let worldx = winW / 2 - (appx + targetX + this.offset.x);
            let worldy = winH / 2 - (appy + targetY + this.offset.y);

            if (worldx > 0) {
                worldx = 0;
            }
            if (winH - worldy > mapH) {
                worldy = winH - mapH;
            }
            if (winW - worldx > mapW) {
                worldx = winW - mapW;
            }
            if (worldy > 0) {
                worldy = 0;
            }
            this._prevPos.x = targetX;
            this._prevPos.y = targetY;
        }
    }

    clamp(mx: number, my: number) {
        
    }
}